import 'package:state_beacon/state_beacon.dart';
import '../models/group_chat_model.dart';
import 'user_state.dart';

/// 团队对话状态管理器
class TeamConversationState {
  // 静态状态变量
  static List<GroupChatModel> _teamGroups = [];
  static List<GroupMessageModel> _teamMessages = [];

  // State Beacon 实例
  static final teamGroupsBeacon = Beacon.writable<List<GroupChatModel>>(
    _teamGroups,
  );
  static final teamMessagesBeacon = Beacon.writable<List<GroupMessageModel>>(
    _teamMessages,
  );

  /// 初始化默认团队数据
  static void _initializeDefaultTeams() {
    if (_teamGroups.isNotEmpty) return; // 避免重复初始化

    // 初始化默认团队群聊数据
    _teamGroups = [
      GroupChatModel(
        groupId: 'team_001',
        groupName: 'Madagascar Wildlife Explorers',
        groupDescription:
            'A community of passionate wildlife enthusiasts exploring Madagascar\'s unique biodiversity',
        groupCoverImage: 'assets/images/ring_tailed_lemur.jpg',
        location: 'Andasibe-Mantadia National Park',
        creatorId: 'user_002',
        memberIds: ['user_002', 'user_003', 'user_004'],
        createTime: DateTime.now().subtract(const Duration(days: 15)),
      ),
      GroupChatModel(
        groupId: 'team_002',
        groupName: 'Baobab Tree Guardians',
        groupDescription:
            'Conservation group dedicated to protecting Madagascar\'s ancient baobab trees',
        groupCoverImage: 'assets/images/baobab_tree.jpg',
        location: 'Avenue of the Baobabs, Morondava',
        creatorId: 'user_003',
        memberIds: [
          'user_002',
          'user_003',
          'user_001',
          'user_005',
          'user_007',
          'user_008',
        ],
        createTime: DateTime.now().subtract(const Duration(days: 8)),
      ),
      GroupChatModel(
        groupId: 'team_003',
        groupName: 'Nocturnal Safari Team',
        groupDescription:
            'Night exploration specialists discovering Madagascar\'s nocturnal creatures',
        groupCoverImage: 'assets/images/aye_aye.jpg',
        location: 'Ranomafana National Park',
        creatorId: 'user_005',
        memberIds: ['user_005', 'user_001', 'user_006', 'user_001', 'user_009'],
        createTime: DateTime.now().subtract(const Duration(days: 5)),
      ),
    ];

    // 初始化默认团队消息数据
    _teamMessages = [
      // Madagascar Wildlife Explorers 群聊消息
      GroupMessageModel(
        messageId: 'team_msg_003',
        groupId: 'team_001',
        senderId: 'user_002',
        content:
            'Amazing! I\'ve been documenting their social behaviors. Did you notice their scent marking patterns on the tree branches?',
        sendTime: DateTime.now().subtract(const Duration(days: 14, hours: 6)),
      ),
      GroupMessageModel(
        messageId: 'team_msg_004',
        groupId: 'team_001',
        senderId: 'user_003',
        content:
            'I captured some incredible footage of a panther chameleon changing colors today. The transformation was so rapid!',
        sendTime: DateTime.now().subtract(const Duration(days: 13)),
      ),
      GroupMessageModel(
        messageId: 'team_msg_006',
        groupId: 'team_001',
        senderId: 'user_004',
        content:
            'I found a beautiful radiated tortoise in the spiny forest today. These ancient creatures are so peaceful.',
        sendTime: DateTime.now().subtract(const Duration(days: 11)),
      ),
      GroupMessageModel(
        messageId: 'team_msg_008',
        groupId: 'team_001',
        senderId: 'user_002',
        content:
            'Yes! I spotted a family of indris near the waterfall trail. Their songs are absolutely mesmerizing.',
        sendTime: DateTime.now().subtract(const Duration(days: 10, hours: 3)),
      ),

      // Baobab Tree Guardians 群聊消息
      GroupMessageModel(
        messageId: 'team_msg_009',
        groupId: 'team_002',
        senderId: 'user_002',
        content:
            'Welcome to the Baobab Tree Guardians! Our mission is to protect these ancient giants for future generations.',
        sendTime: DateTime.now().subtract(const Duration(days: 8)),
      ),
      GroupMessageModel(
        messageId: 'team_msg_010',
        groupId: 'team_002',
        senderId: 'user_001',
        content:
            'Thank you for inviting me! I\'m passionate about baobab conservation. These trees are truly the guardians of Madagascar\'s history.',
        sendTime: DateTime.now().subtract(const Duration(days: 7, hours: 12)),
      ),
      GroupMessageModel(
        messageId: 'team_msg_011',
        groupId: 'team_002',
        senderId: 'user_005',
        content:
            'I discovered a new baobab tree location yesterday. Based on the trunk circumference, it\'s estimated to be over 1000 years old!',
        sendTime: DateTime.now().subtract(const Duration(days: 6)),
      ),
      GroupMessageModel(
        messageId: 'team_msg_012',
        groupId: 'team_002',
        senderId: 'user_007',
        content:
            'That\'s incredible! We need to document this for the conservation database. Can you share the GPS coordinates?',
        sendTime: DateTime.now().subtract(const Duration(days: 6, hours: 2)),
      ),
      GroupMessageModel(
        messageId: 'team_msg_013',
        groupId: 'team_002',
        senderId: 'user_008',
        content:
            'I\'ve been working with local communities to establish protected areas around baobab groves. Education is key!',
        sendTime: DateTime.now().subtract(const Duration(days: 5)),
      ),
      GroupMessageModel(
        messageId: 'team_msg_014',
        groupId: 'team_002',
        senderId: 'user_002',
        content:
            'Excellent work everyone! Let\'s plan a group visit to the Avenue of the Baobabs next week for documentation.',
        sendTime: DateTime.now().subtract(const Duration(days: 4)),
      ),
      GroupMessageModel(
        messageId: 'team_msg_015',
        groupId: 'team_002',
        senderId: 'user_001',
        content:
            'I\'ll bring my professional camera equipment. We should capture the baobabs at different times of day.',
        sendTime: DateTime.now().subtract(const Duration(days: 3, hours: 8)),
      ),

      // Nocturnal Safari Team 群聊消息
      GroupMessageModel(
        messageId: 'team_msg_016',
        groupId: 'team_003',
        senderId: 'user_005',
        content:
            'Welcome to the Nocturnal Safari Team! Tonight we\'re exploring the mysterious world of Madagascar\'s night creatures.',
        sendTime: DateTime.now().subtract(const Duration(days: 5)),
      ),
      GroupMessageModel(
        messageId: 'team_msg_017',
        groupId: 'team_003',
        senderId: 'user_001',
        content:
            'Excited to join! I\'ve been studying aye-aye behavior patterns. Their elongated middle finger is fascinating!',
        sendTime: DateTime.now().subtract(const Duration(days: 4, hours: 18)),
      ),
      GroupMessageModel(
        messageId: 'team_msg_018',
        groupId: 'team_003',
        senderId: 'user_006',
        content:
            'I spotted a tenrec family last night! These spiny creatures are so well camouflaged in the moonlight.',
        sendTime: DateTime.now().subtract(const Duration(days: 4, hours: 6)),
      ),
      GroupMessageModel(
        messageId: 'team_msg_019',
        groupId: 'team_003',
        senderId: 'user_001',
        content:
            'Amazing discoveries! The nocturnal ecosystem is so different from what we see during the day.',
        sendTime: DateTime.now().subtract(const Duration(days: 3, hours: 20)),
      ),
      GroupMessageModel(
        messageId: 'team_msg_020',
        groupId: 'team_003',
        senderId: 'user_009',
        content:
            'I recorded some incredible indri calls last night. Their haunting songs echo through the forest in the darkness.',
        sendTime: DateTime.now().subtract(const Duration(days: 3, hours: 4)),
      ),
      GroupMessageModel(
        messageId: 'team_msg_021',
        groupId: 'team_003',
        senderId: 'user_005',
        content:
            'Tonight\'s target: leaf-tailed geckos! They\'re masters of camouflage. Bring your red light torches everyone.',
        sendTime: DateTime.now().subtract(const Duration(days: 2, hours: 19)),
      ),
      GroupMessageModel(
        messageId: 'team_msg_022',
        groupId: 'team_003',
        senderId: 'user_001',
        content:
            'Found three different gecko species! Their ability to blend with tree bark is absolutely incredible.',
        sendTime: DateTime.now().subtract(const Duration(days: 2, hours: 2)),
      ),
      GroupMessageModel(
        messageId: 'team_msg_023',
        groupId: 'team_003',
        senderId: 'user_006',
        content:
            'The night sounds are so different here. Frogs, insects, and the occasional lemur call create an amazing symphony.',
        sendTime: DateTime.now().subtract(const Duration(days: 1, hours: 22)),
      ),
    ];

    // 更新 Beacon 状态
    teamGroupsBeacon.value = List.from(_teamGroups);
    teamMessagesBeacon.value = List.from(_teamMessages);
  }

  /// 初始化状态
  static void initialize() {
    _initializeDefaultTeams();
  }

  /// 创建新团队群聊
  static String createNewTeam({
    required String groupName,
    required String groupDescription,
    required String groupCoverImage,
    required String location,
    required String creatorId,
  }) {
    _initializeDefaultTeams();
    final newGroupId = 'team_${DateTime.now().millisecondsSinceEpoch}';

    final newTeam = GroupChatModel(
      groupId: newGroupId,
      groupName: groupName,
      groupDescription: groupDescription,
      groupCoverImage: groupCoverImage,
      location: location,
      creatorId: creatorId,
      memberIds: [creatorId], // 创建者自动成为成员
      createTime: DateTime.now(),
    );

    _teamGroups.add(newTeam);
    teamGroupsBeacon.value = List.from(_teamGroups);

    return newGroupId;
  }

  /// 加入团队群聊
  static bool joinTeam(String groupId, String userId) {
    _initializeDefaultTeams();
    final groupIndex = _teamGroups.indexWhere(
      (group) => group.groupId == groupId,
    );
    if (groupIndex == -1) return false;

    final group = _teamGroups[groupIndex];
    if (group.memberIds.contains(userId)) return false; // 已经是成员

    final updatedMemberIds = List<String>.from(group.memberIds);
    updatedMemberIds.add(userId);

    _teamGroups[groupIndex] = group.copyWith(memberIds: updatedMemberIds);
    teamGroupsBeacon.value = List.from(_teamGroups);

    return true;
  }

  /// 退出团队群聊
  static bool leaveTeam(String groupId, String userId) {
    _initializeDefaultTeams();
    final groupIndex = _teamGroups.indexWhere(
      (group) => group.groupId == groupId,
    );
    if (groupIndex == -1) return false;

    final group = _teamGroups[groupIndex];
    if (!group.memberIds.contains(userId)) return false; // 不是成员
    if (group.creatorId == userId) return false; // 创建者不能退出

    final updatedMemberIds = List<String>.from(group.memberIds);
    updatedMemberIds.remove(userId);

    _teamGroups[groupIndex] = group.copyWith(memberIds: updatedMemberIds);
    teamGroupsBeacon.value = List.from(_teamGroups);

    return true;
  }

  /// 发送团队消息
  static void sendTeamMessage({
    required String groupId,
    required String senderId,
    required String content,
  }) {
    _initializeDefaultTeams();

    // 检查发送者是否是团队成员
    final group = _teamGroups.firstWhere(
      (group) => group.groupId == groupId,
      orElse: () => throw Exception('Team not found'),
    );

    if (!group.memberIds.contains(senderId)) {
      throw Exception('User is not a member of this team');
    }

    final newMessage = GroupMessageModel(
      messageId: 'team_msg_${DateTime.now().millisecondsSinceEpoch}',
      groupId: groupId,
      senderId: senderId,
      content: content,
      sendTime: DateTime.now(),
    );

    _teamMessages.add(newMessage);
    teamMessagesBeacon.value = List.from(_teamMessages);
  }

  /// 获取团队群聊列表
  static List<GroupChatModel> getAllTeams() {
    _initializeDefaultTeams();
    return _teamGroups;
  }

  /// 根据ID获取团队群聊
  static GroupChatModel? getTeamById(String groupId) {
    _initializeDefaultTeams();
    try {
      return _teamGroups.firstWhere((group) => group.groupId == groupId);
    } catch (e) {
      return null;
    }
  }

  /// 获取用户加入的团队列表
  static List<GroupChatModel> getUserTeams(String userId) {
    _initializeDefaultTeams();
    return _teamGroups
        .where((group) => group.memberIds.contains(userId))
        .toList();
  }

  /// 获取团队消息列表
  static List<GroupMessageModel> getTeamMessages(String groupId) {
    _initializeDefaultTeams();
    return _teamMessages.where((message) => message.groupId == groupId).toList()
      ..sort((a, b) => a.sendTime.compareTo(b.sendTime));
  }

  /// 获取团队最后一条消息
  static GroupMessageModel? getLastTeamMessage(String groupId) {
    _initializeDefaultTeams();
    final messages = getTeamMessages(groupId);
    return messages.isNotEmpty ? messages.last : null;
  }

  /// 删除团队消息
  static bool removeTeamMessage(String messageId) {
    _initializeDefaultTeams();
    final messageIndex = _teamMessages.indexWhere(
      (message) => message.messageId == messageId,
    );
    if (messageIndex == -1) return false;

    _teamMessages.removeAt(messageIndex);
    teamMessagesBeacon.value = List.from(_teamMessages);
    return true;
  }

  /// 删除团队群聊
  static bool removeTeam(String groupId) {
    _initializeDefaultTeams();
    final groupIndex = _teamGroups.indexWhere(
      (group) => group.groupId == groupId,
    );
    if (groupIndex == -1) return false;

    _teamGroups.removeAt(groupIndex);
    teamGroupsBeacon.value = List.from(_teamGroups);

    // 删除该团队的所有消息
    _teamMessages.removeWhere((message) => message.groupId == groupId);
    teamMessagesBeacon.value = List.from(_teamMessages);

    return true;
  }

  /// 更新团队信息
  static bool updateTeamInfo({
    required String groupId,
    String? groupName,
    String? groupDescription,
    String? groupCoverImage,
    String? location,
  }) {
    _initializeDefaultTeams();
    final groupIndex = _teamGroups.indexWhere(
      (group) => group.groupId == groupId,
    );
    if (groupIndex == -1) return false;

    final group = _teamGroups[groupIndex];
    _teamGroups[groupIndex] = group.copyWith(
      groupName: groupName,
      groupDescription: groupDescription,
      groupCoverImage: groupCoverImage,
      location: location,
    );

    teamGroupsBeacon.value = List.from(_teamGroups);
    return true;
  }

  /// 创建群聊
  static bool createTeam({
    required String groupName,
    required String groupDescription,
    required String location,
    required String time,
    required String groupCoverImage,
    required String creatorId,
  }) {
    _initializeDefaultTeams();

    // 生成新的群聊ID
    final groupId = 'team_${DateTime.now().millisecondsSinceEpoch}';

    // 创建新的群聊
    final newGroup = GroupChatModel(
      groupId: groupId,
      groupName: groupName,
      groupDescription: groupDescription,
      groupCoverImage: groupCoverImage,
      location: location,
      creatorId: creatorId,
      memberIds: [creatorId], // 创建者自动加入
      createTime: DateTime.now(),
    );

    // 添加到群聊列表
    _teamGroups.add(newGroup);

    // 更新状态
    teamGroupsBeacon.value = List.from(_teamGroups);
    return true;
  }

  /// 加入群聊
  static bool joinGroup(String groupId, String userId) {
    _initializeDefaultTeams();
    final groupIndex = _teamGroups.indexWhere(
      (group) => group.groupId == groupId,
    );
    if (groupIndex == -1) return false;

    final group = _teamGroups[groupIndex];

    // 检查用户是否已经在群聊中
    if (group.memberIds.contains(userId)) {
      return false; // 用户已经在群聊中
    }

    // 添加用户到群聊成员列表
    final updatedMemberIds = List<String>.from(group.memberIds)..add(userId);
    _teamGroups[groupIndex] = group.copyWith(memberIds: updatedMemberIds);

    // 更新状态
    teamGroupsBeacon.value = List.from(_teamGroups);
    return true;
  }

  /// 根据用户ID获取用户信息（用于显示用户名和头像）
  static Map<String, String>? getUserInfo(String userId) {
    final user = UserState.queryUserById(userId);
    if (user != null) {
      return {'userName': user.userName, 'userAvatar': user.avatar};
    }
    return null;
  }

  // Getters for reactive state
  static ReadableBeacon<List<GroupChatModel>> get teamGroups =>
      teamGroupsBeacon;
  static ReadableBeacon<List<GroupMessageModel>> get teamMessages =>
      teamMessagesBeacon;
}
